<?php
// +----------------------------------------------------------------------
// | ThinkPHP [ WE CAN DO IT JUST THINK ]
// +----------------------------------------------------------------------
// | Copyright (c) 2006-2016 http://thinkphp.cn All rights reserved.
// +----------------------------------------------------------------------
// | Licensed ( http://www.apache.org/licenses/LICENSE-2.0 )
// +----------------------------------------------------------------------
// | Author: 流年 <liu21st@gmail.com>
// +----------------------------------------------------------------------
use think\facade\Request;
// 应用公共文件
//图片地址
function getFullImageUrl($img){
    if($img){
        //如果img第一个字符是/则去掉
        if(substr($img,0,1)=='/'){
            $img=substr($img,1);
        }
        return getUrl() . $img;
    }
    else{
        $img='storage/imges/mo.png';//默认头像
        return getUrl() . $img;
    }
}
function getFullImageUrl2($img){
    if($img){
        //如果img第一个字符是/则去掉
        if(substr($img,0,1)=='/'){
            $img=substr($img,1);
        }
        return getUrl() . $img;
    }
}
function getUrl(){
    $cloud_type=config('-cloudsite.cloud_type')??0;//云存储类型  0本地 1七牛 2腾讯云
    if($cloud_type==1 || $cloud_type==2){
        //七牛云地址
        $domain=config('-cloudsite.domain');
        //如果这个url最后没有/则加上
        if(substr($domain,-1)!='/'){
            $domain=$domain.'/';
        }
        return $domain;
    }
    else{
        //获取当前域名
        $durl=config('-appsite.app_domainname');
        if($durl){
            //如果这个url最后没有/则加上
            if(substr($durl,-1)!='/'){
                $durl=$durl.'/';
            }
            return $durl;
        }
        else{
            $request = Request::instance();
            $url=$request->domain();
            //如果这个url最后没有/则加上
            if(substr($url,-1)!='/'){
                $url=$url.'/';
            }
            return $url;
        }
    }
}
//获取每个商户的config参数,这个参数在config文件夹下面的extra下面的商户id文件夹下面的单个php文件中
function getMerConfig($val){
    //获取商户id 先获取后台的
    $ohyu_merid=session('mall_admin_merid');
    if(!$ohyu_merid){
        $ohyu_merid=session('ohyu_merid');
        if(!$ohyu_merid){
            return config($val);
            return false;
        }
    }
    //如果val格式不对 则返回false
    if(strpos($val,'.')===false){
        return false;
    }
    //分割val字符串
    $arr=explode('.',$val);
    $configs = \think\facade\Config::load('extra/'.$ohyu_merid.'/'.$arr[0], 'config');
    $value = isset($configs[$arr[1]]) ? $configs[$arr[1]] : false;
    return $value;
}
//获取后台商户id 
function getAdminMerid(){
    //获取商户id
    $ohyu_merid=session('mall_admin_merid');
    return $ohyu_merid;
}
//获取前端商户id
function getAppMerid(){
    //获取商户id
    $ohyu_merid=session('ohyu_merid');
    return $ohyu_merid;
}
//向后台发送消息  php start.php start -d
function webpublish($to_uid, $content){
    // 指明给谁推送，为空表示向所有在线用户推送
    //$to_uid = 123;
    $url=config('-appsite.app_domainname');
    //如果这个url最后有/则去掉
    if(substr($url,-1)=='/'){
        $url=substr($url,0,strlen($url)-1);
    }
    // 推送的url地址，使用自己的服务器地址
    $push_api_url = $url.":2121/";
    $post_data = array(
    "type" => "publish",
    "content" => $content,
    "to" => $to_uid, 
    );
    $ch = curl_init ();
    curl_setopt ( $ch, CURLOPT_URL, $push_api_url );
    curl_setopt ( $ch, CURLOPT_POST, 1 );
    curl_setopt ( $ch, CURLOPT_HEADER, 0 );
    curl_setopt ( $ch, CURLOPT_RETURNTRANSFER, 1 );
    curl_setopt ( $ch, CURLOPT_POSTFIELDS, $post_data );
    curl_setopt ($ch, CURLOPT_HTTPHEADER, array("Expect:"));
    $return = curl_exec ( $ch );
    curl_close ( $ch );
    //var_export($return);
}
//获取后台商户的config参数
function getAdminConfig($val){
    //获取商户id 先获取后台的
    $ohyu_merid=session('mall_admin_merid');
    if(!$ohyu_merid){
        return config($val);
    }
    //分割val字符串
    $configs = \think\facade\Config::load('extra/'.$ohyu_merid.'/'.$val, 'config');
    return $configs;
}
function getweburl(){
    //获取当前域名
    $durl=config('-appsite.app_domainname');
    if($durl){
        return $durl;
    }
    else{
        $request = Request::instance();
        $url=$request->domain();
        return $url;
    }
}
/**所有组合  笛卡尔积**/
function cartesian($data){
    $len = count($data);
    for ($i = 0; $i< $len-1; $i++) {
        if ($i === 0) {
            // 数组第一个值
            $result = $data[0];
        }
        $temp = [];
        // 数组第一个值和第二个值组合
        foreach ($result as $res) {
            //数组第二个值...$i+1
            foreach($data[$i+1] as $sec){
                $temp[] = $res . '-' . $sec;
            }
            $result = $temp;
        }
    }
    return $result;
}
function unicode_encode($name)
{
    $name = iconv('UTF-8', 'UCS-2', $name); //windows
    //$name = iconv('UTF-8', 'UCS-2BE', $name); //linux
    $len = strlen($name);
    $str = '';
    for ($i = 0; $i < $len - 1; $i = $i + 2)
    {
        $c = $name[$i];
        $c2 = $name[$i + 1];
        if (ord($c) > 0)
        {   //两个字节的文字
            $str .= '\u'.base_convert(ord($c), 10, 16).str_pad(base_convert(ord($c2), 10, 16), 2, 0, STR_PAD_LEFT);
        }
        else
        {
            $str .= $c2;
        }
    }
    return $str;
}
function createNoncestr($length = 16) {
    $chars = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
    $str = "";
    for($i = 0; $i < $length; $i ++) {
        $str .= substr ( $chars, mt_rand ( 0, strlen ( $chars ) - 1 ), 1 );
    }
    return $str;
}
// 检测上传图片是否包含有非法代码
function check_illegal($image)
{
    if (file_exists($image)) {
        $strs = file_get_contents($image);//将整个文件内容读入到一个字符串中
        $str = strpos($strs,"<?php");
        if($str){
            return false;//有php 可执行文件
        }
        $resource = fopen($image, 'rb');
        $fileSize = filesize($image);
        fseek($resource, 0);
        if ($fileSize > 512) { // 取头和尾
            $hexCode = bin2hex(fread($resource, 512));
            fseek($resource, $fileSize - 512);
            $hexCode .= bin2hex(fread($resource, 512));
        } else { // 取全部
            $hexCode = bin2hex(fread($resource, $fileSize));
        }
        fclose($resource);
        /* 匹配16进制中的 <% ( ) %> */
        /* 匹配16进制中的 <? ( ) ?> */
        /* 匹配16进制中的 <script | /script> 大小写亦可*/
        if (preg_match("/(3c25)|(3c3f.*?706870)|(3C534352495054)|(2F5343524950543E)|(3C736372697074)|(2F7363726970743E)/is", $hexCode)) {
            return false;
        }
    }
    return true;
}
// 过滤危险标签：防SS攻击  composer require ezyang/htmlpurifier
if (!function_exists('remove_xss')) {
    //使用htmlpurifier防范xss攻击
    function remove_xss($string)
    {
        //composer安装的，不需要此步骤。相对index.php入口文件，引入HTMLPurifier.auto.php核心文件
        // require_once './plugins/htmlpurifier/HTMLPurifier.auto.php';
        // 生成配置对象
        $cfg = HTMLPurifier_Config::createDefault();
        // 以下就是配置：
        $cfg->set('Core.Encoding', 'UTF-8');
        // 设置允许使用的HTML标签
        $cfg->set('HTML.Allowed', 'div[style],b,strong,i,em,a[href|title],ul,ol,li,br,p[style],span[style],img[width|height|alt|src],font[color],video[controls][width][height],source[src]');
        // 设置允许出现的CSS样式属性
        //$cfg->set('CSS.AllowedProperties', 'font,font-size,font-weight,font-style,font-family,text-decoration,padding-left,color,background-color,text-align');
        // 设置a标签上是否允许使用target="_blank"
        //$cfg->set('HTML.TargetBlank', TRUE);
        $def = $cfg->getHTMLDefinition(true);
        $def->addElement('video', 'Block', 'Optional: (source, Flow) | (Flow, source) | Flow', 'Common', [
            'src' => 'URI',
            'type' => 'Text',
            'width' => 'Length',
            'height' => 'Length',
            'poster' => 'URI',
            'preload' => 'Enum#auto,metadata,none',
            'controls' => 'Bool',
        ]);
        $def->addElement('source', 'Block', 'Flow', 'Common', [
            'src' => 'URI',
            'type' => 'Text',
        ]);
        // 使用配置生成过滤用的对象
        $obj = new HTMLPurifier($cfg);
        // 过滤字符串
        return $obj->purify($string);
    }
}
/**
 * 文件下载
 * @param $url
 * @param string $absolute_path
 */
function download($url, $absolute_path = '')
{
    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL, $url);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
    curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 30);
    $file = curl_exec($ch);
    curl_close($ch);
    $resource = fopen($absolute_path, 'a');
    fwrite($resource, $file);
    fclose($resource);
}

function dowwximg($url, $absolute_path = ''){
    $curl=curl_init();
    curl_setopt($curl,CURLOPT_URL,$url);
    curl_setopt($curl,CURLOPT_SSL_VERIFYPEER, FALSE);
    curl_setopt($curl,CURLOPT_SSL_VERIFYHOST,FALSE);
    curl_setopt($curl,CURLOPT_RETURNTRANSFER,1);
    $data=curl_exec($curl);
    if(curl_errno($curl)){return 'ERROR'.curl_errno($curl);}
    curl_close($curl);
    $resource = fopen($absolute_path, 'a');
    fwrite($resource, $data);
    fclose($resource);
}
function isWeixin() {
    if (strpos($_SERVER['HTTP_USER_AGENT'], 'MicroMessenger') !== false) {
        return true;
    } else {
        return false;
    }
}
function ismobile()
{
    // 如果有HTTP_X_WAP_PROFILE则一定是移动设备
    if (isset ($_SERVER['HTTP_X_WAP_PROFILE']))
        return true;
    //此条摘自TPM智能切换模板引擎，适合TPM开发
    if (isset ($_SERVER['HTTP_CLIENT']) && 'PhoneClient' == $_SERVER['HTTP_CLIENT'])
        return true;
    //如果via信息含有wap则一定是移动设备,部分服务商会屏蔽该信息
    if (isset ($_SERVER['HTTP_VIA']))
        //找不到为flase,否则为true
        return stristr($_SERVER['HTTP_VIA'], 'wap') ? true : false;
    //判断手机发送的客户端标志,兼容性有待提高 //io.dcloud.UNIOHYU10031  Weex   Android
    if (isset ($_SERVER['HTTP_USER_AGENT'])) {
        $clientkeywords = array(
            'nokia', 'sony', 'ericsson', 'mot', 'samsung', 'htc', 'sgh', 'lg', 'sharp', 'sie-', 'philips', 'panasonic', 'alcatel', 'lenovo', 'iphone', 'ipod', 'blackberry', 'meizu', 'android', 'netfront', 'symbian', 'ucweb', 'windowsce', 'palm', 'operamini', 'operamobi', 'openwave', 'nexusone', 'cldc', 'midp', 'wap', 'mobile'
        );
        //从HTTP_USER_AGENT中查找手机浏览器的关键字
        if (preg_match("/(" . implode('|', $clientkeywords) . ")/i", strtolower($_SERVER['HTTP_USER_AGENT']))) {
            return true;
        }
    }
    //协议法，因为有可能不准确，放到最后判断
    if (isset ($_SERVER['HTTP_ACCEPT'])) {
        // 如果只支持wml并且不支持html那一定是移动设备
        // 如果支持wml和html但是wml在html之前则是移动设备
        if ((strpos($_SERVER['HTTP_ACCEPT'], 'vnd.wap.wml') !== false) && (strpos($_SERVER['HTTP_ACCEPT'], 'text/html') === false || (strpos($_SERVER['HTTP_ACCEPT'], 'vnd.wap.wml') < strpos($_SERVER['HTTP_ACCEPT'], 'text/html')))) {
            return true;
        }
    }
    return false;
}
/**
 * @$data   需要处理的数组
 * @$pid    父级ID
 * @$level  等级
 */
function tree($data, $pid = 0, $level = 0)
{
    static $tree = array();
    foreach ($data as $key => $value) {
        if ($value['parent_id'] == $pid) {
            $value['level'] = $level;
            $tree[] = $value;
            tree($data, $value['id'], $level + 1);
        }
    }
    return $tree;
}
/**
 * 随机字符
 * @param number $length 长度
 * @param string $type 类型
 * @param number $convert 转换大小写
 * @return string
 */
function random($length=6, $type='string', $convert=0){
    $config = array(
        'number'=>'1234567890',
        'letter'=>'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ',
        'string'=>'abcdefghjkmnpqrstuvwxyzABCDEFGHJKMNPQRSTUVWXYZ23456789',
        'all'=>'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890'
    );

    if(!isset($config[$type])) $type = 'string';
    $string = $config[$type];

    $code = '';
    $strlen = strlen($string) -1;
    for($i = 0; $i < $length; $i++){
        $code .= $string[mt_rand(0, $strlen)];
    }
    if(!empty($convert)){
        $code = ($convert > 0)? strtoupper($code) : strtolower($code);
    }
    return $code;
}
//生成token
function lgaddtoken($user,$v='ohyueo'){
    //生成模式
    $time=time();
    $h='@#$';
    //随机码
    $key='www.ohyu.';
    return md5($user.$v.$time.$h);
}
function gettime(){
    return date('Y-m-d H:i:s');
}
function getip(){
    //获取当前域名
    static $realip;
    if(isset($_SERVER)){
        if(isset($_SERVER['HTTP_X_FORWARDED_FOR'])){
            $realip=$_SERVER['HTTP_X_FORWARDED_FOR'];
        }else if(isset($_SERVER['HTTP_CLIENT_IP'])){
            $realip=$_SERVER['HTTP_CLIENT_IP'];
        }else{
            $realip=$_SERVER['REMOTE_ADDR'];
        }
    }else{
        if(getenv('HTTP_X_FORWARDED_FOR')){
            $realip=getenv('HTTP_X_FORWARDED_FOR');
        }else if(getenv('HTTP_CLIENT_IP')){
            $realip=getenv('HTTP_CLIENT_IP');
        }else{
            $realip=getenv('REMOTE_ADDR');
        }
    }
    return $realip;
}
//自定义函数手机号隐藏中间四位
function yc_phone($str){
    $str=$str;
    $resstr=substr_replace($str,'****',3,4);
    return $resstr;
}
//生成订单号
function neworderNumnew(){
    $yCode = array('A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N','O','P','Q');
    $orderSn = $yCode[intval(date('Y')) - 2011] . strtoupper(dechex(date('m'))) . date('d') . substr(time(), -5) . substr(microtime(), 2, 5) . sprintf('%02d', rand(0, 99));
    return $orderSn;
}
//自定义函数手机号隐藏中间四位
function yc_phonex($str){
    $str=$str;
    $resstr=substr_replace($str,'**',3);
    return $resstr;
}
function week($no){
    //获取30天的房型  预订数据
    $weekArr=array("星期日","星期一","星期二","星期三","星期四","星期五","星期六");
    $days=array();
    for($i=0;$i<$no;$i++){
        $days[$i]['time']=date("m-d",strtotime('+'.$i.'day'));
        if ($i==0) {
            $days[$i]['week']= '今天';
        }else{
            $days[$i]['week']= $weekArr[date("w",strtotime('+'.$i.'day'))];
        }
        $days[$i]['wek']= date("w",strtotime('+'.$i.'day'));
        $days[$i]['riqi'] = date("Y-m-d",strtotime('+'.$i.'day'));
        $num = 0;// 这里需要去获取数量 $yuyuedb->where($da)->getField('num');
        if (empty($num)) {
            $num = 2;
        }
        $days[$i]['num']=$num;
    }
    return $days;
}
//获取星期方法
function get_week($date)
{
    //强制转换日期格式
    $date_str = date('Y-m-d', strtotime($date));
    //封装成数组
    $arr = explode("-", $date_str);
    //参数赋值
    //年
    $year = $arr[0];
    //月，输出2位整型，不够2位右对齐
    $month = sprintf('%02d', $arr[1]);
    //日，输出2位整型，不够2位右对齐
    $day = sprintf('%02d', $arr[2]);
    //时分秒默认赋值为0；
    $hour = $minute = $second = 0;
    //转换成时间戳
    $strap = mktime($hour, $minute, $second, $month, $day, $year);
    //获取数字型星期几
    $number_wk = date("w", $strap);
    //自定义星期数组
    $weekArr = array("星期日", "星期一", "星期二", "星期三", "星期四", "星期五", "星期六");
    //获取数字对应的星期
    //return $weekArr[$number_wk];
    return $number_wk;
}
//清理缓存函数
if (!function_exists('delete_dir_file'))
{
    /**
     * 循环删除目录和文件
     * @param string $dir_name
     * @return bool
     */
    function delete_dir_file($dir_name) {
        $result = false;
        if(is_dir($dir_name)){
            if ($handle = opendir($dir_name)) {
                while (false !== ($item = readdir($handle))) {
                    if ($item != '.' && $item != '..') {
                        if (is_dir($dir_name . '/' . $item)) {
                            delete_dir_file($dir_name . '/' . $item);
                        } else {
                            unlink($dir_name . '/' . $item);
                        }
                    }
                }
                closedir($handle);
                if (rmdir($dir_name)) {
                    $result = true;
                }
            }
        }
        return $result;
    }
}
function posturl($url, array $params = array()){
    $data_string = json_encode($params);
    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL, $url);
    curl_setopt($ch, CURLOPT_HEADER, 0);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
    curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 10);
    curl_setopt($ch, CURLOPT_POST, 1);
    curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
    curl_setopt($ch, CURLOPT_POSTFIELDS, $data_string);
    curl_setopt(
        $ch, CURLOPT_HTTPHEADER,
        array(
            'Content-Type: application/json'
        )
    );
    $data = curl_exec($ch);
    curl_close($ch);
    return ($data);
}